local Msg = require("core.Msg")
local CowryConfig = require("excel.Fuli").cowry
local CowryShowConfig = require("excel.Fuli").cowryShow
local ConsumeConfig = require("excel.Fuli").cowryConsume
local FuliDefine = require("fuli.FuliDefine")
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Broadcast = require("broadcast.Broadcast")
local Lang = require("common.Lang")
local ShopHelp = require("shop.ShopHelp")
local ObjHuman = require("core.ObjHuman")
local CowryBagLogic = require("fuli.CowryBagLogic")
local ItemDefine = require("bag.ItemDefine")
local VipLogic = require("vip.VipLogic")
local VipDefine = require("vip.VipDefine")
local ActivityLogicL = require("activity.ActivityLogicL")
local HtmlUtil = require("common.HtmlUtil")
local Log = require("common.Log")

getYinliang = 0
findTimes = 0

--得到今日总的寻宝次数
function getTotalTimes(human)
  return ConsumeConfig[1].totalTimes + VipLogic.getVipTimes(human, VipDefine.VIP_PRIVILEGE_FINDCOWRY)
end
--发送寻宝配置
function sendCowryConfig(human)
  local sendMsg = Msg.gc.GC_FULI_COWRY_CONFIG
  local cache = {}
  Grid.create(cache, ConsumeConfig[1].itemId, 1)
  Grid.makeItem(cache, sendMsg.item, 0, human)
  sendMsg.config[0] = #ConsumeConfig 
  for i=1, #ConsumeConfig do
    sendMsg.config[i].cnt = ConsumeConfig[i].cnt
    sendMsg.config[i].needRMB = ConsumeConfig[i].needYuanbao
  end
  Msg.send(sendMsg, human.fd)
end
--添加到个人寻宝记录
function addCowrySelfRecord(human, item)
  for i=1, #item do
    if human.db.cowryRecordLen >= FuliDefine.FIND_COWRY_MAX_SELF_RECORD then
      human.db.cowryRecordLen = FuliDefine.FIND_COWRY_MAX_SELF_RECORD - 1
    end
    for j = human.db.cowryRecordLen - 1, 0, -1 do
      human.db.cowryRecord[j + 1].id = human.db.cowryRecord[j].id
      human.db.cowryRecord[j + 1].cnt = human.db.cowryRecord[j].cnt
      human.db.cowryRecord[j + 1].bind = human.db.cowryRecord[j].bind
    end
    human.db.cowryRecordLen = human.db.cowryRecordLen + 1
    human.db.cowryRecord[0].id = item[i][1]
    human.db.cowryRecord[0].cnt = item[i][2]
    human.db.cowryRecord[0].bind = item[i][3]
  end
end
--发送个人寻宝记录
function sendCowrySelfRecord(human)
  local sendMsg = Msg.gc.GC_FULI_COWRY_SELF_RECORD
  sendMsg.record[0] = human.db.cowryRecordLen
  local cache = {}  
  for i=1, sendMsg.record[0] do
    Grid.create(cache, human.db.cowryRecord[i -1].id, human.db.cowryRecord[i -1].cnt, human.db.cowryRecord[i -1].bind)
    Grid.makeItem(cache, sendMsg.record[i].item, 0, human)
    sendMsg.record[i].name = ""
    sendMsg.record[i].uuid = ""
  end
  sendMsg.remainCnt = math.max(0, getTotalTimes(human) - human.db.findCowryTimes)
  Msg.send(sendMsg, human.fd)
end

--将寻宝记录发送到world并且全服公告
function sendRecordToWorld(human, item)
  for i=1, #item do
    if CowryConfig[item[i][6]].isShow ~= 0 then
      local sendMsg = Msg.lw.LW_FULI_SET_RECORD
      sendMsg.name = human.name
      sendMsg.uuid = human._id
      sendMsg.id = item[i][1]
      sendMsg.cnt = item[i][2]
      sendMsg.bind = item[i][3]
      Msg.send2world(sendMsg, human._id)
    end
    if CowryConfig[item[i][6]].broadcast ~= 0 then
      local grid = {}      
      grid = Grid.create(grid, item[i][1], item[i][2], true)
      local str = string.format(Lang.FULI_COWRY_CENTER_BRO, HtmlUtil.fontName(human.name, human._id), HtmlUtil.fontItem(grid), human._id)
      Broadcast.sendBroadcast2World(Lang.UP + Lang.GROSSIP, str)
    end
  end  
end
--奖励列表
function getRewardList(human)
  local sendMsg = Msg.gc.GC_FULI_REWARD
  local cache = {}
  sendMsg.list[0] = #CowryShowConfig
  for i=1, #CowryShowConfig do
    sendMsg.list[i].page = FuliDefine.FULI_TYPE_COWRY
    sendMsg.list[i].canGet = 0
    sendMsg.list[i].vipCanGet = 0
    sendMsg.list[i].condition = 0
    sendMsg.list[i].needYuanbao = 0
    sendMsg.list[i].reward[0] = 1
    Grid.create(cache, CowryShowConfig[i].reward, 1)
    Grid.makeItem(cache, sendMsg.list[i].reward[1], 0, human)
    sendMsg.list[i].vipReward[0] = 0 
    sendMsg.list[i].onlineTime = 0     
    sendMsg.list[i].percent = 0
  end
  Msg.send(sendMsg, human.fd)
  sendCowrySelfRecord(human)
  sendCowryConfig(human)
end
--清空每日寻宝次数
function updateStatus(human)
  human.db.cowryGetMaxCntLen = 0  --每日最大抽中次数清0
  human.db.findCowryTimes = 0 --每次寻宝次数清 0
end
--判断是否可计算权重
function canUseWeight(human, index, findType)
  if not human.fcTmp then human.fcTmp = {} end  
  if CowryConfig[index].maxTimes ~= 0 then
    for i=0, human.db.cowryGetMaxCntLen - 1 do
      if human.db.cowryGetMaxCnt[i].maxGetIndex == index and human.db.cowryGetMaxCnt[i].maxGetTimes >= CowryConfig[index].maxTimes then        
        return false
      end
    end
  end 
  return isWeightTimes(human, index, findType)
end
--判断是权重次数是否足够
function isWeightTimes(human, index, findType)
  if CowryConfig[index].times ~= 0 and human.db.findCowryTimes <= CowryConfig[index].times then
    return false
  end
  return getWeight(human, index, findType) ~= 0
end
--每日最大寻宝次数+1
function addDailyMax(human)
  for i=1, #human.fcTmp do
    local has = false
    for j=0, human.db.cowryGetMaxCntLen - 1 do
      if human.db.cowryGetMaxCnt[j].maxGetIndex == human.fcTmp[i] and CowryConfig[human.fcTmp[i]].maxTimes ~= 0 then
        has = true
        human.db.cowryGetMaxCnt[j].maxGetTimes = human.db.cowryGetMaxCnt[j].maxGetTimes + 1
      end
    end
    if not has then      
      human.db.cowryGetMaxCnt[human.db.cowryGetMaxCntLen].maxGetIndex = human.fcTmp[i]
      human.db.cowryGetMaxCnt[human.db.cowryGetMaxCntLen].maxGetTimes = 1
      human.db.cowryGetMaxCntLen = human.db.cowryGetMaxCntLen + 1
      if human.db.cowryGetMaxCntLen > 65 then
        human.db.cowryGetMaxCntLen = 65
      end 
    end
  end
  human.fcTmp = {}
end

--得到物品抽取权重。index：配置表索引，type:0是道具抽奖，1是元宝抽奖
function getWeight(human, index, findType)
  if CowryConfig[index].isSpecial == 1 and human.db.cowrySpecTimes >= ConsumeConfig[1].specialTimes then
    return (findType == 1 and CowryConfig[index].YuanbaoWeight or CowryConfig[index].itemWeight)
  elseif  CowryConfig[index].isSpecial ~= 1 and human.db.cowrySpecTimes < ConsumeConfig[1].specialTimes then 
    return (findType == 1 and CowryConfig[index].YuanbaoWeight or CowryConfig[index].itemWeight)
  end    
  return 0
end
--寻宝几率
function getRandCowry(human, findType, type)
  local item = {}  
  if type > 1 and findTimes <= 1 then
    if type == 2 then
      for i=1, 5 do
        if getYinliang < 10 * i * 10000 then
          item[1] = 10107
          item[2] = 6 - i
          item[3] = 1
          item[6] = 4
          return item
        end
      end      
    elseif type == 3 then
      for i=1, 5 do
        if getYinliang < 50 * i * 10000 then
          item[1] = 10109
          item[2] = 6 - i
          item[3] = 1
          item[6] = 6
          return item
        end
      end
    end
  end
  findTimes = findTimes - 1  
  local totalRand = 0
  for i=1, #CowryConfig do
    if canUseWeight(human, i, findType) then
      totalRand = totalRand + getWeight(human, i, findType)
    end
  end
  local randWeight = math.random(1, totalRand)
  totalRand = 0
  for i=1, #CowryConfig do
    if canUseWeight(human, i, findType) then
      totalRand = totalRand + getWeight(human, i, findType)
      if randWeight <= totalRand then
        item = CowryConfig[i].reward
        if item[1] == 30007 or item[1] == 30037 or item[1] == 30017 then
          Log.write(Log.LOGID_TEST, randWeight, totalRand)
        end
        item[3] = math.random(1, 100) <= CowryConfig[i].bindRand and 1 or 0
        item[6] = i
        if findType == 0 then
          item[3] = 1
        end
        human.db.cowrySpecTimes = human.db.cowrySpecTimes + 1            
        if human.db.cowrySpecTimes > ConsumeConfig[1].specialTimes then
          human.db.cowrySpecTimes = 0
        end
        if CowryConfig[i].maxTimes ~= 0 then
          human.fcTmp[#human.fcTmp + 1] = i
        end
        if item[1] >= 10101 and item[1] < 10115 then
          getYinliang = getYinliang + ItemDefine.getValue(item[1], "price")
        end
        return item
      end
    end
  end
end

--发送寻宝得到的道具
function sendGetItemInfo(human, item)
  local sendMsg = Msg.gc.GC_FULI_COWRY_SHOW
  sendMsg.itemDatas[0] = #item
  local cache = {}
  for i=1, #item do
    Grid.create(cache, item[i][1], item[i][2], item[i][3])
    Grid.makeItem(cache, sendMsg.itemDatas[i], 0, human)
  end
  Msg.send(sendMsg, human.fd)
end
--临时函数
local function func(tmpTable, item)
  local isEqure = false
  for j=1, #tmpTable do
    if tmpTable[j][1] == item[1] and ItemDefine.canAppend(item[1]) then
      isEqure = true
      tmpTable[j][2] = tmpTable[j][2] + item[2]
    end
  end
  if not isEqure then
    tmpTable[#tmpTable + 1] = {}
    tmpTable[#tmpTable][1] = item[1]
    tmpTable[#tmpTable][2] = item[2]
  end
end
--创建table，用来判断是否可以添加到寻宝背包中
function makeTable(human, item)
  local tmp = {}
  for i=1, #item do
    func(tmp, item[i])
  end
  return tmp
end

--元宝寻宝
function yuanbaoFind(human, type, item)
  if not CowryBagLogic.checkCanAddItemList(human, makeTable(human, item)) then
    human.fcTmp = {}
    Broadcast.sendBroadcast(human, Lang.DOWN, Lang.FULI_COWRY_BAG_FULL)
    return false
  end
  for i=1, #item do
    CowryBagLogic.addItem(human, item[i][1], item[i][3], item[i][2])
  end
  sendGetItemInfo(human, item)
  addCowrySelfRecord(human, item)
  return true
end
--锦囊寻宝入口
function findCowry(human, type)
  if human.db.findCowryTimes + ConsumeConfig[type].cnt > getTotalTimes(human) then
    return Broadcast.sendBroadcast(human, Lang.DOWN, Lang.FULI_COWRY_MAX_TIMES)
  end
  getYinliang = 0
  findTimes = ConsumeConfig[type].cnt 
  local cost = 0
  local useCnt = 0
  local item = {}
  local specTimes = human.db.cowrySpecTimes
  local itemCnt = BagLogic.getItemCount(human, ConsumeConfig[1].itemId)
  local oneItemYuanbao = math.floor(ConsumeConfig[type].needYuanbao / ConsumeConfig[type].cnt)
  if itemCnt >= 1 then
    local useYuanbao = 0
    useCnt = ConsumeConfig[type].cnt
    if itemCnt < useCnt then
      useCnt = itemCnt
    end
    for i=1, useCnt do
      item[i] = getRandCowry(human, 0, type)    
    end
        
    if ConsumeConfig[type].cnt - useCnt > 0 then
      if not ObjHuman.checkYuanbaoEnough(human, oneItemYuanbao * (ConsumeConfig[type].cnt - useCnt)) then
        return ShopHelp.onNoRMB(human)
      else
        useYuanbao = oneItemYuanbao * (ConsumeConfig[type].cnt - useCnt)
        for i=1, ConsumeConfig[type].cnt - useCnt do
          item[#item + 1] = getRandCowry(human, 1, type)
        end
        human.db.findCowryTimes = human.db.findCowryTimes + ConsumeConfig[type].cnt - useCnt        
      end
    end
    human.db.findCowryTimes = human.db.findCowryTimes + useCnt
    if not yuanbaoFind(human, type, item) then
      human.db.cowrySpecTimes = specTimes
      return
    else
      BagLogic.delItemsById(human, ConsumeConfig[1].itemId, useCnt, "fulidating")
      ObjHuman.decYuanbao(human, useYuanbao, "fulidating")
    end
    cost = useYuanbao 
  else
    if not ObjHuman.checkYuanbaoEnough(human, ConsumeConfig[type].needYuanbao) then
      return ShopHelp.onNoRMB(human)
    end
    for i=1, ConsumeConfig[type].cnt do
      item[i] = getRandCowry(human, 1, type)
    end
    if not yuanbaoFind(human, type, item) then
      human.db.cowrySpecTimes = specTimes
      return
    else
      ObjHuman.decYuanbao(human, ConsumeConfig[type].needYuanbao, "fulidating")
    end
    cost = ConsumeConfig[type].needYuanbao 
    human.db.findCowryTimes = human.db.findCowryTimes + ConsumeConfig[type].cnt    
  end
  Broadcast.sendBroadcast(human, Lang.DOWN, Lang.FULI_COWRY_FIND_SUCCESS)
  addDailyMax(human)
  sendRecordToWorld(human, item)
  sendCowrySelfRecord(human)
  getRewardList(human)
  getYinliang = 0
  findTimes = 0
  
  Log.write(Log.LOGID_OSS_FIND_COWRY, human._id, human.account, human.name,human.db.lv, type, cost, useCnt)
  ActivityLogicL.updateActivityValue(human, "find_cowry") 
end















